<template>
    <div>
        <SuperTable ref="table" path="/order/delivery/index" :params="params" :columns="columns" @on-selection-change="handleSelectionChange">
            <div slot="header-right">
                <Form ref="filter" :model="filter" inline>
                    <FormItem label="关键词">
                        <Input v-model="filter.keywords" clearable placeholder="订单号、快递单号" style="width: 200px;" />
                    </FormItem>
                    <FormItem label="发货人" prop="sender">
                        <Select v-model="filter.sender" clearable style="width: 80px">
                            <Option value="partner">商家</Option>
                            <Option value="platform">平台</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="收货人" prop="receiver">
                        <Select v-model="filter.receiver" clearable style="width: 80px">
                            <Option value="user">用户</Option>
                            <Option value="platform">平台</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="打印状态" prop="is_print">
                        <Select v-model="filter.is_print" clearable style="width: 80px">
                            <Option :value="0">未打印</Option>
                            <Option :value="1">已打印</Option>
                        </Select>
                    </FormItem>
                    <FormItem label="状态" prop="status">
                        <Select v-model="filter.status" clearable style="width: 80px">
                            <Option :value="-1">已驳回</Option>
                            <Option :value="0">待审核</Option>
                            <Option :value="1">已审核</Option>
                        </Select>
                    </FormItem>
                    <Button type="primary" @click="handlFilter">筛选</Button>
                </Form>
            </div>
            <div slot="page-left">
                <Button type="success" :disabled="selectedOrders.length == 0" @click="batchPrint">批量打印面单</Button>
            </div>
        </SuperTable>

        <Modal title="纸质票审核" v-model="showModal" :width="600" @on-cancel="handleCancel">
            <div class="order-card">
                <div class="title">发货信息</div>
                <div class="content">
                    <div class="cell">
                        <div class="label">商家：</div>
                        <div class="value">{{ curInfo.partner.name }}</div>
                    </div>
                    <div class="cell">
                        <div class="label">配送方式：</div>
                        <div class="value">{{ curInfo.delivery_type_text }}</div>
                    </div>
                    <div class="cell">
                        <div class="label">发货对象：</div>
                        <div class="value">{{ curInfo.sender == 'partner' ? '商家' : '平台' }}</div>
                    </div>
                    <div class="cell">
                        <div class="label">收货对象：</div>
                        <div class="value">{{ curInfo.receiver == 'user' ? '用户' : '平台' }}</div>
                    </div>
                    <div class="cell" v-if="curInfo.receiver == 'platform'">
                        <div class="label">收票地址：</div>
                        <div class="value">{{ curInfo.platform_address }}</div>
                    </div>
                    <div class="cell" v-if="curInfo.delivery_type == 1">
                        <div class="label">快递名称：</div>
                        <div class="value">{{ curInfo.express_name }}</div>
                    </div>
                    <div class="cell" v-if="curInfo.delivery_type == 1">
                        <div class="label">快递单号：</div>
                        <div class="value">{{ curInfo.express_sn }}</div>
                    </div>
                    <div class="cell" v-if="curInfo.delivery_type == 2">
                        <div class="label">取票地址：</div>
                        <div class="value">{{ curInfo.pick_address }}</div>
                    </div>
                    <div class="cell" v-if="curInfo.delivery_type == 2">
                        <div class="label">取票联系方式：</div>
                        <div class="value">{{ curInfo.pick_phone }}</div>
                    </div>
                    <div class="cell">
                        <div class="label">截图：</div>
                        <div class="value">
                            <ImageView :imgs="curInfo.imgs"></ImageView>
                        </div>
                    </div>
                </div>
            </div>
            <div class="order-card">
                <div class="title">观演人</div>
                <div class="content" style="marginLeft:40px">
                    <div v-for="item in curInfo.order_info.contact_info" :key="item.id">
                        <Tag color="blue">{{ item.name }} <span style="margin: 0 10px">{{ item.type === 1 ? '身份证' : '其他' }}</span> {{ item.number }}</Tag>
                    </div>
                </div>
            </div>
            <div class="order-card">
                <div class="title">收票信息</div>
                <div class="content">
                    <div class="cell">
                        <div class="label">姓名：</div>
                        <div class="value">
                            {{ curInfo.order_info.buyer_name }}
                        </div>
                    </div>
                    <div class="cell">
                        <div class="label">手机号：</div>
                        <div class="value">
                            {{ curInfo.order_info.phone }}
                        </div>
                    </div>
                    <div v-if="curInfo.order_info.delivery_type == 2" class="cell">
                        <div class="label">联系地址：</div>
                        <div class="value">
                            {{ curInfo.order_info.area_titles }} {{ curInfo.order_info.address }}
                        </div>
                    </div>
                </div>
            </div>
            <Form ref="form" :model="form" :rules="rules" :label-width="80">
                <FormItem label="状态" prop="status" required>
                    <RadioGroup v-model="form.status">
                        <Radio :disabled="curInfo.status != 0" :label="1">通过</Radio>
                        <Radio :disabled="curInfo.status != 0" :label="-1">驳回</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancel">取消</Button>
                <Button :disabled="curInfo.status != 0" type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
            </div>
        </Modal>

        <Modal title="快递轨迹信息" v-model="showRoutesModal" :width="600" @on-cancel="showRoutesModal = false" scrollable>
            <Timeline>
                <TimelineItem v-for="item in routes">
                    <p class="time">{{item.acceptTime}}</p>
                    <p class="content">{{item.remark}}</p>
                </TimelineItem>
            </Timeline>
            <div slot="footer">
                <Button @click="showRoutesModal = false">关闭</Button>
            </div>
        </Modal>

        <Modal
        v-model="confirmPrintModal"
        :title="'已选择'+selectedOrders.length+'条，过滤后剩余'+confirmPrintOrders.length+'条可打印，关闭弹窗后自动刷新状态！'"
        :width="1200"
        >
            <Table :width="1170" :columns="columnsPrint" :data="confirmPrintOrders"></Table>
            <div slot="footer">
                <Button @click="handleCancelPrintModal">关闭</Button>
                <Button type="primary" @click="handleConfirmPrint">提交</Button>
            </div>
        </Modal>
        <Modal
        v-model="printerModal"
        title="选择打印机">
            <Form :label-width="84">
                <FormItem label="打印机：" required>
                    <Select v-model="printer_val" style="width: 280px;">
                        <Option v-for="item in printerItems" :key="item.id" :value="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button @click="printerModal = false">关闭</Button>
                <Button type="primary" @click="handleBatchPrint">提交</Button>
            </div>
        </Modal>

    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import ImageView from '@/components/form/image-view.vue';
import SCPPrint from '../../../static/SCPPrint.js';
export default {
    components: {
        SuperTable,
        TableRows,
        ImageView
    },
    data() {
        return {
            selectedOrders: [],
            //轨迹
            routes: [],
            showRoutesModal: false,
            //打印
            printer_val: null,
            printSdk: {},
            printToken: '',
            printerItems: [],
            printerModal: false,
            //顺丰批量打印
            confirmPrintOrders: [],
            confirmPrintModal: false,
            columnsPrint: [
                {
                    title: "序号",
                    type: "index",
                    align: "center",
                    width: 54
                },
                {
                    title: '订单信息',
                    minWidth: 120,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`订单号：${params.row.order_sn}`),
                            h('p',`商家单号：${params.row.partner_osn || '-'}`)
                        ])
                    }
                },
                {
                    title: '票档信息',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.order_info.project_name}`),
                            h('p',[
                                h('span',`${params.row.order_info.concert_name + '  ' + params.row.order_info.sku_name}` + '  '),
                                h('span', {style:{color:'red'}}, `${params.row.order_info.number}张`)
                            ]),
                        ])
                    }
                },
                {
                    title: '购买信息',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`委托价：${params.row.order_info.partner_sku_price}`),
                            h('p',[
                                h('Tag', {
                                    props: {
                                        color: params.row.order_info.delivery_type == 1 ? 'blue' : 'green'
                                    }
                                }, params.row.order_info.delivery_type == 1 ? '电子票' : '纸质票')
                            ]),
                        ])
                    }
                },
                {
                    title: '状态',
                    width: 80,
                    key: 'status_text'
                },
                {
                    title: '打印状态',
                    width: 80,
                    render: (h, params) => {
                        return h('Span', params.row.is_print == 0 ? '未打印' : '已打印');
                    }
                },
                {
                    title: '操作',
                    width: 94,
                    render: (h, params) => {
                        return h('Button', {
                            props: {
                                size: 'small',
                                type: 'error'
                            },
                            on: {
                                click: () => {
                                    this.confirmDeliveryOrders.splice(params.index, 1);
                                }
                            }
                        }, '删除');
                    }
                }
            ],
            submiting: false,
            showModal: false,
            form: {
                id: '',
                status: 1,
            },
            rules: {},
            curInfo: {
                partner:{},
                order_info: {
                    contact_info: []
                }
            },
            filter: {
                keywords: '',
                sender: '',
                receiver: '',
                is_print: '',
                status: '',
            },
            params: {
                page: 1,
                pageSize: 10
            },
            columns: [
                {
                    type: 'selection',
                    width: 50,
                    align: 'center'
                },
                {
                    title: '订单信息',
                    minWidth: 120,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`订单号：${params.row.order_sn}`),
                            h('p',`商家单号：${params.row.partner_osn || '-'}`)
                        ])
                    }
                },
                {
                    title: '票档信息',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.order_info.project_name}`),
                            h('p',[
                                h('span',`${params.row.order_info.concert_name + '  ' + params.row.order_info.sku_name}` + '  '),
                                h('span', {style:{color:'red'}}, `${params.row.order_info.number}张`)
                            ]),
                        ])
                    }
                },
                {
                    title: '商家&类型',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`商家：${params.row.partner.name}`),
                            h('p',`类型：${params.row.delivery_type_text}`),
                        ])
                    }
                },
                {
                    title: '发货人&收货人',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`发货人：${params.row.sender == 'partner' ? '商家' : '平台'}`),
                            h('p',`收货人：${params.row.receiver == 'user' ? '用户' : '平台'}`),
                        ])
                    }
                },
                {
                    title: '快递&单号',
                    minWidth: 100,
                    render: (h, params) => {
                        let spans = [
                            h('span',`${params.row.express_sn || '-'}`)
                        ];
                        if (params.row.express_sn){
                            spans.push(
                                h("a",{
                                    style: {marginLeft: '3px'},
                                    on: {
                                        click: () => {
                                            this.$ajax.get('/expressApi/sf_routes',{params: {express_sn: params.row.express_sn}}).then(res => {
                                                this.routes = res;
                                                this.showRoutesModal = true;
                                            }).catch(err => {
                                                this.$Message.error(err.message || '获取轨迹失败');
                                            })
                                        }
                                    }
                                },'轨迹')
                            );
                        }
                        return h(TableRows, [
                            h('p',`${params.row.express_name || '-'}`),
                            h('p',spans)
                        ])
                    }
                },
                {
                    title: '创建时间&状态',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.created_at}`),
                            h('p',`${params.row.status_text}`),
                        ])
                    }
                },
                {
                    title: '面单打印',
                    render: (h, params) => {
                        return h('span',params.row.is_print == 1 ? '已打印' : '未打印')
                    }
                },
                {
                    title: "操作",
                    align: "center",
                    key: "action",
                    width: 120,
                    render: (h, params) => {
                        return h("div", [
                            h("Button", {
                                props: {
                                    type: "primary",
                                    size: "small",
                                },
                                on: {
                                    click: () => {
                                        this.curInfo = params.row;
                                        this.form.id = params.row.id;
                                        this.showModal = true;
                                    }
                                }
                            }, params.row.status == 0 ? "审核" : "查看")
                        ])
                    }
                }
            ]
        }
    },
    mounted() {
        if ('status' in this.$route.query) {
            this.filter.status = this.$route.query.status;
            this.params.status = this.$route.query.status;
            this.$refs.table.init();
        }
        this.printInit();
    },
    methods: {
        handleSelectionChange(selections){
            this.selectedOrders = selections
        },
        printInit() {
            //实例化
            const sdkCallback = result => {};
            let sdkParams = {
                partnerID: 'PDZQCTK0B33A',
                env: 'sbox',//上线时修改为：pro
                callback: sdkCallback,
                notips: false
            }
            this.printSdk = new SCPPrint(sdkParams);
            // 获取打印机
            const getPrintersCallback = result => {
              if (result.code === 1) {
                result.printers.map(item =>{
                    let _obj = {
                        name: item.name,
                        id: item.index,
                    }
                    this.printerItems.push(_obj);
                });
              }
            };
            this.printSdk.getPrinters(getPrintersCallback);
            //获取token
            this.$ajax.get('/order/delivery/sf_token').then(res => {
                this.printToken = res.accessToken;
            }).catch(err => {
                this.$Message.error(err.message || '获取打印token失败');
            })
        },
        handlFilter() {
            const { filter } = this;
            this.params.keywords = filter.keywords;
            this.params.sender = filter.sender;
            this.params.receiver = filter.receiver;
            this.params.is_print = filter.is_print;
            this.params.status = filter.status;
            this.$refs.table.init();
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    const { form } = this;
                    let params = {
                        id: form.id,
                        status: form.status,
                    }
                    this.submiting = true;
                    this.$ajax.post('/order/delivery/audit', params).then(res => {
                        this.$Message.success('操作成功');
                        this.submiting = false;
                        this.handleCancel();
                        this.$refs.table.init();
                    }).catch(err => {
                        this.submiting = false;
                        this.$Message.error(err.message || '操作失败');
                    })
                }
            })
        },
        handleCancel() {
            this.showModal = false;
            setTimeout(() => {
                this.form.id = '';
                this.form.status = 1;
            }, 300)
        },
        //顺丰批量打印
        batchPrint(){
            this.confirmPrintModal = true;
            let _lists = [];
            this.selectedOrders.map(item =>{
                if (item.status == 1 && item.receiver == 'user' && item.express_identify == 'SF'){
                    _lists.push(item);
                }
            })
            this.confirmPrintOrders = _lists;
        },
        handleConfirmPrint(){
            if (!this.confirmPrintOrders.length){
                this.$Message.error('暂无可打印的数据');
                return false;
            }
            this.printerModal = true;
        },
        handleBatchPrint(){
            if (this.printer_val == null){
                this.$Message.error('请先选择打印机');
                return false;
            }
            this.printerModal = false;
            this.printSdk.setPrinter(this.printer_val);
            //执行打印
            let billInfo = [];
            let ids = [];
            this.confirmPrintOrders.map(item => {
                ids.push(item.id);
                let _obj = {
                    masterWaybillNo: item.express_sn,
                    customData:{
                        'spec_name': '场次：'+item.order_info.concert_name + ' ' + item.order_info.sku_name,
                        'order_sn': '订单号：'+item.order_sn,
                        'number': '数量：'+item.order_info.number+'张',
                    }
                }
                billInfo.push(_obj);
            })
            let data = {
                requestID: Date.parse(new Date()),
                accessToken: this.printToken,
                templateCode: "fm_76130_standard_PDZQCTK0B33A",
                templateVersion: "",
                documents: billInfo,
                extJson: {},
                customTemplateCode: "fm_76130_standard_custom_10028279829_1"
            };
            var that = this;
            const callback = function(result) {
                if (result.code == 1){
                    //批量标记打印
                    that.$ajax.post('/order/delivery/confirm_print', {ids: ids}).then((res) => {
                        setTimeout(() => {
                            that.$Message.success(ids.length+'条数据打印成功');
                            that.handleCancelPrintModal();
                        }, 1000)
                    }).catch((err) => {
                    })
                }
            };
            const options = {
                lodopFn: "PRINT"
            };
            this.printSdk.print(data, callback, options);
        },
        handleCancelPrintModal(){
            this.confirmPrintModal = false
            this.$refs.table.reload();
        },
    }
}
</script>

<style lang="less" scoped>
.order-card {
    margin-bottom: 20px;
    .title {
        font-size: 14px;
        font-weight: bold;
    }
    .content {
        margin-top: 10px;
        .cell {
            padding: 6px 0;
            line-height: 20px;
            font-size: 14px;
            overflow: hidden;
            .label {
                float: left;
                width: 100px;
                text-align: right;
                color: #666;
            }
        }
    }
}
</style>